﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UICompos : MonoBehaviour
{
    public List<GameObject> btnList = new List<GameObject>();
    private Dictionary<string, GameObject> dic = new Dictionary<string, GameObject>();

    private void Awake()
    {
        for (int i = 0; i < btnList.Count; i++)
        {
            if (dic.ContainsKey(btnList[i].name))
            {
                dic[btnList[i].name] = btnList[i];
            }
            else
            {
                dic.Add(btnList[i].name, btnList[i]);
            }
        }
    }

//    public string this[]{}
//    [__DynamicallyInvokable]
    public UICompos this[string key]
    {
        get { return Get(key).GetComponent<UICompos>(); }
    }

    public GameObject Get(string name)
    {
        if (!dic.ContainsKey(name))
        {
            return null;
        }

        return dic[name];
    }

    public T GetComps<T>()
    {
        return gameObject.GetComponent<T>();
    }

#if UNITY_EDITOR

    [ContextMenu("添加到对应的上面")]
    public void AppendToChild()
    {
        btnList.Clear();
        List<Transform> childs = new List<Transform>();

        for (int i = 0; i < transform.childCount; i++)
        {
            childs.Add(transform.GetChild(i));
        }


        foreach (var VARIABLE in childs)
        {
            var comps = VARIABLE.GetComponent<UICompos>();
            if (!comps)
            {
                comps = VARIABLE.gameObject.AddComponent<UICompos>();
            }

            comps.AppendToChild();
            btnList.Add(VARIABLE.gameObject);
        }
    }
#endif
}